package com.dm.wallpaper.library.utils;


import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.abilityPackage.WallpaperBoardApplication;
import com.dm.wallpaper.library.helpers.WallpaperHelper;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.dm.wallpaper.library.utils.downfile.ProgressDownloader;
import com.dm.wallpaper.library.utils.downfile.ProgressResponseBody;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVLoggerConnection;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import static com.dm.wallpaper.library.utils.SystemUtils.vp2px;

/*
 * Wallpaper Board
 *
 * Copyright (c) 2017 Dani Mahardhika
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class WallpaperDownloader implements ProgressResponseBody.ProgressListener {

    /**
     * breakPoints
     */
    private long breakPoints;

    /**
     * contentLength
     */
    private long contentLength;

    private final Context mContext;

    private Wallpaper mWallpaper;

    private ProgressDownloader downloader;

    private WallpaperDownloader(Context context) {
        mContext = context;
    }

    public WallpaperDownloader wallpaper(Wallpaper wallpaper) {
        mWallpaper = wallpaper;
        return this;
    }

    public void start() {
        String fileName = mWallpaper.getName() + "." + WallpaperHelper.getFormat(mWallpaper.getMimeType());
        File directory = WallpaperHelper.getDefaultWallpapersDirectory(mContext);
        File target = new File(directory, fileName);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                try {
                    String string = mContext.getResourceManager().getElement(ResourceTable.String_wallpaper_download_failed).getString();
                    Toast.show(mContext, string);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // showCafeBar(R.string.wallpaper_download_failed);
                return;
            }
        }

        if (WallpaperHelper.isWallpaperSaved(mContext, mWallpaper)) {
            Log.i("hh", "Wallpaper already downloaded");
            try {
                String string = mContext.getResourceManager().getElement(ResourceTable.String_wallpaper_already_downloaded).getString();

                Toast.InitToastLayout initToastLayout = new Toast.InitToastLayout() {
                    @Override
                    public Component initToastLayout(Context context) {
                        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_toast_open, null, false);
                        ((Text) component.findComponentById(ResourceTable.Id_content)).setText("Wallpaper already downloaded");

                        Component contentLayout = component.findComponentById(ResourceTable.Id_content_layout);
                        contentLayout.setBackground(Toast.buildDrawableByColorRadius(Color.getIntColor("#70000000"), vp2px(mContext, 20)));
                        component.findComponentById(ResourceTable.Id_open).setClickedListener(o -> {
                            String uri = Preferences.get().getVelueByKey(fileName);
                            if (uri.equals("")) {
                                Toast.show(mContext, "not found picture");
                            } else {
                                Uri uri11 = Uri.parse(uri.replace("dataability:/", "content:"));
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
                                intent.setType("image/*");
                                intent.setUri(uri11);
                                mContext.startAbility(intent, AbilityInfo.AbilityType.PAGE.ordinal());
                            }
                        });
                        return component;
                    }
                };

                DialogUtils.getInstance().showToastBottom(mContext, initToastLayout);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        if (!isValidURL(mWallpaper.getUrl())) {
            Log.i("hh", "Download: wallpaper url is not valid");
            return;
        }

        downloader = new ProgressDownloader(mWallpaper.getUrl(), target, this, 0);
        downloader.download(0);
        Log.i("hh", "开始下载");
        Toast.show(mContext, "开始下载");
    }

    private boolean isValidURL(String urlString) {
        Log.i("hh", "urlString " + urlString);
        try {
            return true;
        } catch (Exception exception) {
            Log.i("hh", "exception " + exception.getMessage());
            return false;
        }
    }



    public static WallpaperDownloader prepare(Context context) {
        return new WallpaperDownloader(context);
    }

    @Override
    public void onPreExecute(long contentLength, int piston) {
        if (this.contentLength == 0L) {
            this.contentLength = contentLength;
            Log.i("hh", "contentLength " + contentLength);
            //  mContext.getUITaskDispatcher().asyncDispatch(() -> {
            // progressBar.setMaxValue((int) (contentLength / 1024));
            // });
        }
    }

    @Override
    public void update(long totalBytes, boolean done, int piston) {
// 注意加上断点的长度

        Log.i("hh", "totalBytes  " + (totalBytes + breakPoints));
        //  mContext.getUITaskDispatcher().asyncDispatch(() -> {
        //  progressBar.setProgressValue((int) (totalBytes + breakPoints) / 1024);
        //  });

        //TODO 将图片加入到相册


        if (done) {

            PixelMap imageSource = ImageSource.create(getFile(), new ImageSource.SourceOptions()).createPixelmap(null);
            Uri uri = SystemUtils.saveImage(getFile().getName(), imageSource, WallpaperBoardApplication.getInstance());

            Toast.InitToastLayout initToastLayout = new Toast.InitToastLayout() {
                @Override
                public Component initToastLayout(Context context) {
                    Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_toast_open, null, false);
                    ((Text) component.findComponentById(ResourceTable.Id_content)).setText("下载完成");

                    Component contentLayout = component.findComponentById(ResourceTable.Id_content_layout);
                    contentLayout.setBackground(Toast.buildDrawableByColorRadius(Color.getIntColor("#70000000"), vp2px(mContext, 20)));
                    component.findComponentById(ResourceTable.Id_open).setClickedListener(o -> {
                        Uri uri11 = Uri.parse(uri.toString().replace("dataability:/", "content:"));
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
                        intent.setType("image/*");
                        intent.setUri(uri11);
                        mContext.startAbility(intent, AbilityInfo.AbilityType.PAGE.ordinal());
                    });
                    return component;
                }
            };

            // 切换到主线程
            Log.i("hh", "下载完成  ");
            mContext.getUITaskDispatcher().asyncDispatch(() -> {
//                Toast.show(mContext, Toast.ToastLayout.BOTTOM, initToastLayout);
                DialogUtils.getInstance().showToastBottom(mContext, initToastLayout);
                performLoggerFile();
            });
        }
    }


    private File getFile() {
        String type = WallpaperHelper.getFormat(mWallpaper.getMimeType());
        String fileName = mWallpaper.getName() + "." + type;
        File directory = WallpaperHelper.getDefaultWallpapersDirectory(mContext);
        File target = new File(directory, fileName);


        return target;
    }
    // AVLoggerConnection avLoggerConnection;

    private void performLoggerFile() {
        File target = getFile();
        String mimeType = mWallpaper.getMimeType();
        if (mimeType == null || mimeType.length() == 0) {
            mimeType = "image/jpeg";
        }
        Log.i("hh", "performLoggerFile " + target.length());
        //TODO 无法扫描进相册 why?
//        avLoggerConnection = new AVLoggerConnection(mContext, new AVLoggerConnectionClient() {
//            @Override
//            public void onLoggerConnected() {
//                Log.i("hh", "onLoggerConnected ");
//                avLoggerConnection.performLoggerFile(target.getPath(), mimeType);
//            }
//
//            @Override
//            public void onLogCompleted(String s, Uri uri) {
//                avLoggerConnection.disconnect();
//                Log.i("hh", "onLogCompleted " + s);
//            }
//        });
//        avLoggerConnection.connect();
        try {
            AVLoggerConnection.performLoggerFile(mContext, new String[]{target.getCanonicalPath()}, new String[]{mimeType}, (s, uri) -> {
                //
                Log.i("hh", "onLogCompleted " + s);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
